package com.dome.user.config;


import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.dome.client.config.exception.FeignException;
import com.dome.client.config.result.enums.RtnResultCodeEnums;
import feign.Response;
import feign.Util;
import feign.codec.ErrorDecoder;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.context.annotation.Configuration;

import java.io.IOException;
import java.util.Scanner;

/**
 * feign异常处理
 *
 * @author:JZ
 * @date:2020/5/16
 */
@Configuration
@Slf4j
public class UserFeignErrorDecoder implements ErrorDecoder {

    public static void main(String[] args) {

        for (int i = 2; i <=10 ; i++) {
            if(i%2==0){
                System.out.println(i+"不是素数");
                continue;
            }
            System.out.println(i+"是素数");
        }
       /* System.out.println("请输入要进行判断的整数：");
        Scanner sc = new Scanner(System.in);
        int number = sc.nextInt();
        System.out.println("您输入的整数是：" + number);
        if (isPrimeNumber(number)) {
            System.out.println("您输入的数" + number + "是素数。");
        } else {
            System.out.println("您输入的数" + number + "不是是素数。");
        }*/
    }

    //判断素数的静态方法
    public static boolean isPrimeNumber(int num) {
        boolean flag = true;
        if (num == 2) {
            return flag;
        }
        for (int i = 1; i < Math.sqrt(num); i++) {
            if (num % 2 == 0) {
                flag = false;
                break;
            }
        }
        return flag;
    }



    @Override
    public FeignException decode(String s, Response response) {
        FeignException feignException = new FeignException(RtnResultCodeEnums.SERVICE_EXCEPTION.getMsgCN());
        try {
            String errorContent = Util.toString(response.body().asReader());
            if (StringUtils.isBlank(errorContent)) {
                return feignException;
            }
            JSONObject jsonObject = JSON.parseObject(errorContent);
            return new FeignException(jsonObject.toJSONString());
        } catch (IOException e) {
            log.error("处理FeignClient 异常错误");
            e.printStackTrace();
        }
        return feignException;
    }


}

